using MongoDB.Driver;
using System;
using System.Configuration;
using SmartLink.Domain.MongoEntity;

namespace SmartLink.MongoHelper
{
    /// <summary>
    /// Represents the MongoDB repository context.
    /// </summary>
    public class MongoDBRepositoryContext : IMongoDBRepositoryContext
    {
        private readonly IMongoDBRepositoryContextSettings settings;
        private readonly MongoClient client;
        private readonly IMongoDatabase db;

        /// <summary>
        /// 构造，初始化MongoClient
        /// </summary>
        /// <param name="settings"></param>
        public MongoDBRepositoryContext(IMongoDBRepositoryContextSettings settings)
        {
            this.settings = settings;
            client = new MongoClient(settings.ClientSettings);
            db = client.GetDatabase(settings.DatabaseName);
        }

        /// <summary>
        /// Mongo 设置
        /// </summary>
        public IMongoDBRepositoryContextSettings Settings
        {
            get
            {
                return settings;
            }
        }

        /// <summary>
        /// 获取一个集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IMongoCollection<T> GetCollection<T>() where T : IEntity
        {
            return db.GetCollection<T>(typeof(T).Name);
        }

        /// <summary>
        /// 获取Id 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>序列ID</returns>
        public int getNextSequence<T>()
        {
            //此处代码需要优化，应该一个API方法就可以搞定
            var collection = db.GetCollection<Counter>("counter");

            string name = typeof(T).Name;
            var filter = Builders<Counter>.Filter.Where(t => t.id == name);
            var last = collection.Find(filter).FirstOrDefaultAsync().Result;
            if (last == null)
            {
                collection.InsertOneAsync(new Counter() { id = name, seq = 0 });
            }

            var def = Builders<Counter>.Update.Inc(t => t.seq, 1);
            collection.FindOneAndUpdateAsync(filter, def).Wait();
            return collection.Find(filter).FirstOrDefaultAsync().Result.seq;

        }

        /// <summary>
        /// 清除序列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void ClearSequence<T>()
        {
            var collection = db.GetCollection<Counter>("counter");

            string name = typeof(T).Name;
            var filter = Builders<Counter>.Filter.Where(t => t.id == name);
            var def = Builders<Counter>.Update.Set(t => t.seq, 0);
            collection.FindOneAndUpdateAsync(filter, def).Wait();
        }
    }

    /// <summary>
    /// 序列
    /// </summary>
    public class Counter
    {
        /// <summary>
        /// 类型的Id
        /// </summary>
        public string id { get; set; }

        /// <summary>
        /// 当前的序列
        /// </summary>
        public int seq { get; set; }
    }
}
